import request from '@/utils/request'

// WebSocket 连接
let ws = null // WebSocket实例
let messageCallback = null // 消息回调函数
let reconnectAttempts = 0 // 重连尝试次数
const MAX_RECONNECT_ATTEMPTS = 3 // 最大重连次数
const RECONNECT_INTERVAL = 3000 // 重连间隔(毫秒)

// 初始化 WebSocket 连接
export const initWebSocket = (callback) => {
  messageCallback = callback
  const token = localStorage.getItem('token')
  if (!token) {
    console.error('No token found')
    return
  }

  // 创建 WebSocket 连接
  ws = new WebSocket(`ws://localhost:8066/customer?token=${token}`)

  ws.onopen = () => {
    console.log('WebSocket connected')
    reconnectAttempts = 0 // 重置重连次数
  }

  ws.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data)
      if (messageCallback) {
        messageCallback(message)
      }
    } catch (error) {
      console.error('Error parsing message:', error)
    }
  }

  ws.onerror = (error) => {
    console.error('WebSocket error:', error)
  }

  ws.onclose = () => {
    console.log('WebSocket disconnected')
    // 尝试重连
    if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
      setTimeout(() => {
        reconnectAttempts++
        initWebSocket(callback)
      }, RECONNECT_INTERVAL)
    }
  }
}

// 发送消息
export const sendMessage = (message) => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    // 直接发送消息，不再添加 sender，因为已经在组件中设置
    ws.send(JSON.stringify(message))
    return true
  } else {
    console.error('WebSocket is not connected')
    return false
  }
}

// 关闭 WebSocket 连接
export const closeWebSocket = () => {
  if (ws) {
    ws.close()
    ws = null
    messageCallback = null
  }
}

// 获取连接状态
export const getConnectionState = () => {
  if (!ws) return 'CLOSED'
  switch (ws.readyState) {
    case WebSocket.CONNECTING:
      return 'CONNECTING'
    case WebSocket.OPEN:
      return 'OPEN'
    case WebSocket.CLOSING:
      return 'CLOSING'
    case WebSocket.CLOSED:
      return 'CLOSED'
    default:
      return 'UNKNOWN'
  }
}

// 获取历史消息
export const getHistoryMessages = (sender, receiver) => {
  return request({
    url: '/chat/history',
    method: 'get',
    params: {
      sender,
      receiver
    }
  })
}

// 获取客服列表
export const getCustomerServiceList = () => {
  return request({
    url: '/customer/list',
    method: 'get'
  })
} 